import type { ListKey } from '@/indexDB/types'
import { assetsDB } from '@/indexDB/index'
import { computed, ref } from "vue"

export interface ListConfig {
  listKey: ListKey
  pageSize?: number
}

export type AimType = 'add' | 'edit' | 'detail'

const DIALOG_TITLE_MAP: Record<AimType, string> = {
  'add': '新增',
  'edit': '编辑',
  'detail': '详情'
}

export const useList = <ItemType extends Record<string, any> = Record<string, any>>(config: ListConfig) => {
  const { listKey, pageSize } = config
  const list = ref<ItemType[]>()

  const pageInfo = ref({
    pageSize: pageSize ?? 10,
    pageNum: 1,
    total: 0
  })


  const init = () => {
    assetsDB[listKey].where('id').above(0).sortBy('createTime').then((arr: unknown) => {
      list.value = arr as ItemType[]
    })
  }
  init()

  const activeItem = ref<ItemType>()
  const showDialog = ref(false)

  const aim = ref<AimType>('edit')

  const dialogTitle = computed(() => {
    return DIALOG_TITLE_MAP[aim.value]
  })

  const toDetail = (info: ItemType) => {
    aim.value = 'detail'
    showDialog.value = true
    activeItem.value = info
  }

  const toEdit = (info: ItemType) => {
    aim.value = 'edit'
    showDialog.value = true
    activeItem.value = info
  }

  const handleEdit = (form: ItemType) => {
    const data = JSON.parse(JSON.stringify(form))
    return assetsDB[listKey]
      .put(data)
      .then(() => {

        init()
        showDialog.value = false
      })

  }

  const toAdd = () => {
    aim.value = 'add'
    showDialog.value = true
    activeItem.value = undefined
  }

  const handleAdd = (form: ItemType) => {
    const data = JSON.parse(JSON.stringify(form))
    return assetsDB[listKey]
      .add(data)
      .then(() => {
        init()
        showDialog.value = false
      })

  }

  const handleConfirm = (form: ItemType) => {
    if (aim.value === 'detail') {
      showDialog.value = false
      return Promise.resolve()
    }

    if (aim.value === 'add') {
      return handleAdd(form)
    }

    if (aim.value === 'edit') {
      return handleEdit(form)
    }

  }

  return {
    aim,
    list,
    activeItem,
    showDialog,
    dialogTitle,
    toEdit,
    toAdd,
    toDetail,
    handleEdit,
    handleConfirm,
    handleAdd,
    pageInfo
  }
}